#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 数据库操作相关

from sqlalchemy.orm import Session
from fastapi import HTTPException
from .models import *
from .schemas import *


def get_users_method(db: Session, skip: int = 0, limit: int = 10):
    return db.query(User).offset(skip).limit(limit).all()

def get_user_method(db: Session, uid: int):
    user = db.query(User).filter(User.id == uid).first()
    if not user:
        raise HTTPException(status_code=404, detail="user not exists")
    return user


def create_user_method(db: Session, user: UserModel):
    db_user = db.query(User).filter(User.email == user.email).first()
    if db_user:
        raise HTTPException(status_code=200, detail="this user already exists")
    fake_hashed_password = user.password + "_hashed"
    init_user = User(email=user.email, hashed_password=fake_hashed_password)
    db.add(init_user)
    db.commit()
    db.refresh(init_user)
    return init_user


def get_items_method(db: Session, skip: int = 0, limit: int = 10):
    return db.query(Item).offset(skip).limit(limit).all()


def get_items_by_uid_method(db: Session, uid: int, skip: int = 0, limit: int = 10):
    user = db.query(User).filter(User.id == uid).first()
    if not user:
        raise HTTPException(status_code=200, detail="this user is not valid")
    return db.query(Item).filter(Item.owner == user).offset(skip).limit(limit).all()


def create_item_by_user_method(db: Session, uid: int, item: ItemModel):
    # 先查询uid用户是否存在
    get_user_method(db, uid)
    init_item = Item(**item.model_dump(), owner_id=uid)
    db.add(init_item)
    db.commit()
    db.refresh(init_item)
    return init_item
